import os, re
from configparser import RawConfigParser


def get_config(file_name='config', sections=[], key=[], sections_filter=[], key_filter=[], sec_regx='', k_regx=''):
    file_name = f"{file_name}.ini"
    dir_path = os.path.dirname(os.path.dirname(__file__))
    path = os.path.join(dir_path, "config", file_name)
    cf = RawConfigParser()
    cf.read(path, encoding='utf-8')

    if not sections:
        sections = cf.sections()

    if isinstance(sections, str):
        sections = [sections]
    if isinstance(sections_filter, str):
        sections_filter = [sections_filter]
    if isinstance(key_filter, str):
        key_filter = [key_filter]
    sections = set(sections) - set(sections_filter)

    result = {}
    key_flags = False
    for section in sections:
        try:
            if key:
                key_flags = True
                if isinstance(key, str):
                    key = [key]
                for k in key:
                    data = cf.get(section, k, fallback=None)
                    if not data:
                        continue
                    if not result.get(section, ''):
                        result[section] = {}
                    result[section].update({
                        k: eval(data)
                    })
            else:
                options = cf.items(section)
                result.update({
                    section: {option[0]: eval(option[1]) for option in options if option[0] not in key_filter}
                })
        except Exception as e:
            print(e)
            result.update({section: {}})
    if sec_regx or k_regx:
        result = get_regx(result, sec_regx, k_regx)
    result = get_value(result, key_flags)
    return result


def get_regx(result, sec_regx, k_regx):
    new_result = {}
    for k, _item in result.items():
        if sec_regx:
            if not re.search(sec_regx, k):
                continue
        tmp_dict = _item
        if k_regx:
            tmp_dict = {kk: v for kk, v in _item.items() if re.search(k_regx, kk)}
        if tmp_dict:
            new_result.update({k: tmp_dict})
    return new_result


def get_value(result, key_flags=False):
    if isinstance(result, dict) and len(result) == 1:
        value = list(result.values())[0]
        if isinstance(value, dict) or key_flags:
            return get_value(value, key_flags)
    return result


if __name__ == "__main__":
    conf = get_config(sections="base").get("spider_map", "")